package com.jinpeng.common.aspect;

import com.jinpeng.common.annotation.TargetDataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


/**
 * 动态数据源切换类
 */

@Aspect
//该切面应当先与@Transactional执行
@Order(-1)
@Component
public class DynamicDataSourceAspect {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    //匹配com.jinpeng.*.service包及其子包下的所有类的所有方法
    @Pointcut("execution(* com.jinpeng.*.service..*.*(..))")
    public void pointCut() {

    }

    /**
     * 执行方法前更换数据源
     *
     * @param joinPoint 切点
     * @throws Exception
     */
    @Before("@annotation(targetDataSource)")
    public void switchDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) throws Exception {
        if (!DynamicDatasourceHolder.containDataSourceKey(targetDataSource.value())) {
            //DynamicDatasourceHolder.containsDataSourceType(targetDataSource.value());
            log.info("默认数据源： " + targetDataSource.value());
        } else {
            //切换数据源
            DynamicDatasourceHolder.setDataSourceType(targetDataSource.value());
            log.info("切换数据源： " +
                    DynamicDatasourceHolder.getDataSourceType() + joinPoint.getSignature());
        }
    }


    /**
     * 执行方法后清除数据源设置
     *
     * @param joinPoint 切点
     */
    @After("@annotation(targetDataSource)")
    public void restoreDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        DynamicDatasourceHolder.clearDataSourceType();
        log.info("清除数据源： " +
                DynamicDatasourceHolder.getDataSourceType() + joinPoint.getSignature());
    }

}
